package com.whfc.iot.context;

import com.whfc.common.spring.AppContextUtil;
import com.whfc.iot.autoconfigure.BrokerProperties;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import com.whfc.iot.session.SessionSynchronizer;
import com.whfc.iot.session.impl.SessionManagerImpl;
import com.whfc.iot.session.impl.SessionSynchronizerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Description: 环境全局配置
 * @author: xugcheng
 * @version: 1.0
 * @date: 2020-12-03 14:29
 */
@Configuration
public class HjContext {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 初始session保存数量
     */
    public static final int ONLINE_SESSIONS = 256;

    @Autowired
    private BrokerProperties brokerProperties;

    @Bean
    public SessionManager sessionManager() {
        ConcurrentMap<String, Session> channelId2sessionMap = new ConcurrentHashMap<>(ONLINE_SESSIONS);
        ConcurrentMap<String, String> deviceId2channelIdMap = new ConcurrentHashMap<>(ONLINE_SESSIONS);
        SessionManager sessionManager = new SessionManagerImpl(channelId2sessionMap, deviceId2channelIdMap);
        return sessionManager;
    }

    @Bean
    public SessionSynchronizer sessionSynchronizer() {
        SessionSynchronizer synchronizer = new SessionSynchronizerImpl(brokerProperties.getName(), sessionManager());
        synchronizer.run();
        return synchronizer;
    }

    @Bean
    @ConditionalOnMissingBean
    public AppContextUtil appContextUtil() {
        return new AppContextUtil();
    }
}
